using NLog;
using NLog.Config;
using NLog.Targets;
using System;
using System.Diagnostics;
using UnityEngine;

public static class UnityLog
{
    private static NLog.Logger logger;

    public static void Startup()
    {
        LoggingConfiguration config = new LoggingConfiguration();

        FileTarget logfile = new FileTarget("logfile")
        {
            FileName = $"{Application.dataPath}/../Logs/{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.log",
            Layout = "[${time}][${event-properties:frame}][${level}]: ${message} ${exception}",
        };
        config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);

        LogManager.Configuration = config;

        logger = LogManager.GetCurrentClassLogger();
    }

    public static void StartupEditor()
    {
        LoggingConfiguration config = new LoggingConfiguration();
        UnityConsoleTarget logconsole = new UnityConsoleTarget()
        {
            Layout = "[${time}][${event-properties:frame}][${level}]: ${message} ${exception}",
        };
        config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole);

        FileTarget logfile = new FileTarget("logfile")
        {
            FileName = $"{Application.dataPath}/../Logs/{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.log",
            Layout = "[${time}][${event-properties:frame}][${level}]: ${message} ${exception}",
        };
        config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);
        LogManager.Configuration = config;

        logger = LogManager.GetCurrentClassLogger();
    }

    public static void Teardown()
    {
        LogManager.Shutdown();
    }

    [Conditional("LOG")]
    public static void Info(string message)
    {
        if (logger == null)
            return;

        logger.SetProperty("frame", Time.frameCount);
        logger.Info(message);
    }

    [Conditional("LOG")]
    public static void Warn(string message)
    {
        if (logger == null)
            return;

        logger.SetProperty("frame", Time.frameCount);
        logger.Warn(message);
    }

    public static void Error(string message)
    {
        if (logger == null)
            return;

        logger.SetProperty("frame", Time.frameCount);
        logger.Error(message);
    }

    public static void Fatal(string message)
    {
        if (logger == null)
            return;

        logger.SetProperty("frame", Time.frameCount);
        logger.Fatal(message);
    }
}
